package com.lecoboy.highconcurrency.threaddemo;

import java.util.concurrent.TimeUnit;

/**
 * 线程的状态demo
 */
public class ThreadState {
    /**
     * 启动后打开命令窗口
     * jps 会输出
     * <p>
     * 2145 Jps
     * 705 GradleDaemon
     * 2133 Launcher
     * 1029 GradleDaemon
     * 2134 ThreadState
     * 635
     * 860 GradleDaemon
     * </p>
     *
     * 使用 jstack 2134 查看堆栈，即可看到线程运行状态
     *
     * @param args
     */
    public static void main(String[] args) {
        new Thread(new TimeWaiting(),"TimeWaitingThread").start();
        new Thread(new Waiting(),"WaitingThread").start();
        // 使用两个Blocked线程，一个获取锁成功，另一个被阻塞
        new Thread(new Blocked(),"BlockedThread-1").start();
        new Thread(new Blocked(),"BlockedThread-2").start();
    }
    // 该线程不断的进行睡眠
    static class TimeWaiting implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //该线程在Waiting.class实例上等待
    static class Waiting implements Runnable{

        @Override
        public void run() {
            while (true){
                synchronized (Waiting.class){
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    // 该线程在Blocked.class实力上加锁后，不会释放该锁
    static class Blocked implements Runnable{

        @Override
        public void run() {
            synchronized (Blocked.class){
                while (true){
                    try {
                        TimeUnit.SECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
